﻿using System;
using System.Net;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;

namespace Inmeta.TFS.MergeWorkItemsEventHandler
{
    public class ImpersonatedCollection
    {
        public static TfsTeamProjectCollection CreateImpersonatedCollection(Uri collectionToUse, string userToImpersonate)
        {
            NetworkCredential cred = CredentialCache.DefaultNetworkCredentials;
            var currentCollection = new TfsTeamProjectCollection(collectionToUse, cred);
            var identityManagementService = currentCollection.GetService<IIdentityManagementService>();

            // Look up the user that we want to impersonate
            TeamFoundationIdentity identity = identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, userToImpersonate, MembershipQuery.None, ReadIdentityOptions.None);
            var impersonatedCollection = new TfsTeamProjectCollection(collectionToUse, new TfsClientCredentials(), identity.Descriptor);
            return impersonatedCollection;
        }
    }

}
